package org.advanced.security;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author John.zhang
 * @version Id: Atomised, v 1.0 2020/12/7 19:42 ZhiYong Exp $
 * 禁止重排序(volatile)保证原子性
 */
public class Atomised {

    public static int count = 0;

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public synchronized static void inc() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //这里的count实际经历三个指令 --javap -v Atomised.class (getstatic/iadd/putstatic)
        //count++;//(实际只会一个线程来执行)
        atomicInteger.incrementAndGet();//Atomic工具类来保证原子性
    }





    public static void main(String[] args) {
        int max = 100;
        for (int i = 0; i < max; i++) {
            new Thread(Atomised::inc).start();
        }
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
}
